import Layout from '@/layouts/index.vue'
import ParentView from '@/components/ParentView/index.vue';
import { asyncRoutes, constantRoutes ,asyncStaticRoutes} from '@/router';
import { getResouceList } from '@/api/router';
import { convertRouter, filterAsyncRoutes } from '@/utils/handleRoutes';
import Cookies from 'js-cookie';
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue')

const state = () => ({
  routes: [],
  apiRoutes:[],
  api2Routes:Cookies.get("api2Routes")?JSON.parse(Cookies.get("api2Routes")):[],
  currentColumnId: "",
  currentRouteId: "",
  isOpend:false,
  isOpen2:false,
  partialRoutes: [],
});
const getters = {
  routes: (state) => state.routes,
  apiRoutes: (state) => state.apiRoutes,
  api2Routes: (state) => state.api2Routes,
  currentColumnId: (state) => state.currentColumnId,
  currentRouteId: (state) => state.currentRouteId,
  isOpend: (state) => state.isOpend,
  isOpend2: (state) => state.isOpend2,
  partialRoutes: (state) => state.partialRoutes,
};
const mutations = {
  setRoutes(state, routes) {
    state.routes = constantRoutes.concat(routes);
  },
  setApiRoutes(state, routes) {
   let arr=[]
    routes.forEach((item,i) => {
      if(item.name=="Root"){
       
      }else{
        arr.push(item)
      }

    });
    state.apiRoutes = arr;
  },
  api2Routes(state, arr) {
    Cookies.set("api2Routes", JSON.stringify(arr));
     state.api2Routes = arr;
   },
   setCurrentColumnId(state, arr) {
    state.currentColumnId = arr;
  },
  setIsOpend(state, arr) {
    state.isOpend = arr;
  },
  setIsOpen2(state, arr) {
    state.isOpend2 = arr;
  },
  setCurrentRouteId(state, arr) {
    state.currentRouteId = arr;
  },
  setAllRoutes(state, routes) {
    state.routes = constantRoutes.concat(routes);
  },
  setPartialRoutes(state, routes) {
    state.partialRoutes = constantRoutes.concat(routes);
  },
};
const actions = {
  async setRoutes({ commit }, permissions) {
    //开源版只过滤动态路由permissions，admin不再默认拥有全部权限
    const finallyAsyncRoutes = await filterAsyncRoutes([...asyncRoutes], permissions);
    commit('setRoutes', finallyAsyncRoutes);
    return finallyAsyncRoutes;
  },
  async setAllRoutes({ commit }) {
    let { data } = await getResouceList();
    // data.push({ path: '*', redirect: '/404', hidden: true });
    const countRoute=asyncStaticRoutes.concat(filterAsyncRouter(data))
    let accessRoutes = convertRouter(countRoute);
    console.log(accessRoutes,"路由")
    commit('setApiRoutes', accessRoutes);
    commit('setAllRoutes', accessRoutes);
    return accessRoutes;
  },
  setPartialRoutes({ commit }, accessRoutes) {
    commit('setPartialRoutes', accessRoutes);
    return accessRoutes;
  },
};
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      return () => modules[path]();
    }
  }

}
export default { state, getters, mutations, actions };
